﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

namespace UDS.Web.UI.Controls
{
    public class DateTextBox : TextBox
    {
        private CalendarButton _button;
        private CalendarExtender _extender;

        /// <summary>
        /// ctor.
        /// </summary>
        public DateTextBox()
        {
            Format = "yyyy-MM-dd";
        }

        /// <summary>
        /// Gets or sets the date format.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        [DefaultValue("yyyy-MM-dd")]
        public string Format
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the text content of the control.
        /// </summary>
        public override string Text
        {
            get
            {
                if (ReadOnly && Context != null && Page != null && Page.IsPostBack)
                {
                    var value = Context.Request[ClientID];
                    if (value != null)
                    {
                        return value;
                    }
                }
                return base.Text;
            }
        }

        /// <summary>
        /// Gets or sets the parsed date.
        /// </summary>
        public DateTime SelectedDate
        {
            get
            {
                DateTime date;
                if (DateTime.TryParse(Text, out date))
                {
                    return date;
                }
                return DateTime.MinValue;
            }
            set { Text = value.ToString(Format); }
        }

        /// <summary>
        /// Init the control.
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            _button = new CalendarButton();
            _button.TargetControlID = ID;
            Controls.Add(_button);

            _extender = new CalendarExtender();
            _extender.TargetControlID = ID;
            _extender.Format = Format;
            _extender.Animated = true;
            Controls.Add(_extender);

            base.OnInit(e);
        }

        /// <summary>
        /// Renders the control.
        /// </summary>
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            writer.WriteLine();
            _button.RenderControl(writer);
            _extender.RenderControl(writer);
        }
    }
}